<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width layout="vertical">
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="customerId"
                label="客户"
                :rules="[{ required: true, message: '请输入客户名称' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect
                  v-model="form.customerId"
                  placeholder="输入客户名进行搜索"
                  allow-search
                  @change="formEvent('customerID')"
                >
                  <AOption
                    v-for="item in customerList"
                    :key="item.customerId"
                    :label="item.customerName"
                    :value="item.customerId"
                  ></AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem
                field="detailList"
                label="送货单"
                :rules="[{ required: true, message: '请输入送货单' }]"
                :validate-trigger="['change', 'blur']"
                :pagination="false"
                :content-flex="false"
              >
                <div class="erp-mb-5">
                  <AButton type="primary" @click="tableBtn('addRow')">添加送货单</AButton>
                </div>
                <ATable
                  :data="form.detailList"
                  :bordered="{ cell: true }"
                  :scroll="{ maxHeight: 300 }"
                  :pagination="false"
                  column-resizable
                  size="small"
                >
                  <template #columns>
                    <ATableColumn title="送货单号" data-index="deliveryOrderId" :width="150">
                      <template #cell="{ record }">
                        <ASelect
                          v-model="record.deliveryOrderId"
                          allow-search
                          placeholder="选择送货单"
                          @change="tableBtn('changeRelated', record)"
                        >
                          <AOption
                            v-for="item in deliveryList"
                            :key="item.deliveryOrderId"
                            :label="item.deliveryOrderCode"
                            :value="item.deliveryOrderId"
                          ></AOption>
                        </ASelect>
                      </template>
                    </ATableColumn>
                    <ATableColumn title="送货日期" data-index="deliveryDate" :width="150">
                      <template #cell="{ record }">
                        <span v-if="record.deliveryDate">
                          {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
                        </span>
                      </template>
                    </ATableColumn>
                    <ATableColumn title="产品名称" data-index="materialName" :width="150">
                      <template #cell="{ record }">
                        {{ record.detailList.map((item) => item.materialName).join(',') }}
                      </template>
                    </ATableColumn>
                    <ATableColumn title="金额" data-index="amt" :width="150">
                      <template #cell="{ record }">
                        {{ sumBy(record.detailList, 'amt') }}
                      </template>
                    </ATableColumn>
                    <ATableColumn
                      v-if="form.detailList.length > 1"
                      title="操作"
                      data-index="amt"
                      :width="80"
                      align="center"
                      fixed="right"
                    >
                      <template #cell="{ record, rowIndex }">
                        <AButton
                          status="danger"
                          size="mini"
                          @click="tableBtn('delRow', record, rowIndex)"
                        >
                          删除
                        </AButton>
                      </template>
                    </ATableColumn>
                  </template>
                </ATable>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="invoiceAmt" label="票据金额">
                <AInputNumber
                  v-model="form.invoiceAmt"
                  model-event="input"
                  placeholder="票据金额"
                  hide-button
                  :precision="2"
                  :step="0.1"
                />
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="remark" label="状态">
                <ASelect v-model="form.remark" allow-search placeholder="状态">
                  <AOption value="已开票">已开票</AOption>
                  <AOption value="已作废">已作废</AOption>
                  <AOption value="待开票">待开票</AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="attachFiles" label="附件">
                <upload v-model:attachFiles="attachFiles"></upload>
              </AFormItem>
            </ACol>
            <ACol>
              <AFormItem field="remark" label="备注">
                <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
              </AFormItem>
            </ACol>
          </ARow>
        </AForm>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { deleteNullObject } from '@renderer/utils/data-processing'
import upload from '@renderer/components/upload/index.vue'
import {
  editInvoice,
  getInvoiceDetail,
  InvoiceReq,
  InvoiceResItem,
  InvoiceResItemDetailList
} from '@renderer/api/invoiceManage'
import { DeliveryListSearch, DeliveryResItem, getDeliveryAllList } from '@renderer/api/logisticsDep'
import { CustomerResItem, getCustomerAllList } from '@renderer/api/company'
import { differenceBy, isEmpty, sumBy } from 'lodash-es'
import { useMenuState } from '@renderer/store'
import { FileListType } from '@renderer/types/global'
import { batchDelUploadFile } from '@renderer/api/common'

interface Props {
  [key: string]: any
  checkData?: Partial<InvoiceResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<InvoiceReq>({
  invoiceCode: '',
  customerId: '',
  invoiceDate: '',
  invoiceAmt: 0,
  invoiceStatus: 0,
  invoiceType: 1,
  remark: '',
  detailList: [],
  fileList: []
})
const attachFiles = ref<FileListType[]>([])
const tableRow = ref<InvoiceResItemDetailList>({
  deliveryDate: '',
  purchaseDate: '',
  productName: '',
  amt: 0,
  purchaseOrderId: '',
  purchaseOrderCode: '',
  deliveryOrderId: '',
  deliveryOrderCode: ''
})
const menuParam = useMenuState()

// 获取客户
const customerList = ref<CustomerResItem[]>([])
const getCustomerList = async () => {
  const res = await getCustomerAllList({})
  customerList.value = res.data.list
}
// 获取送货单
const deliveryList = ref<DeliveryResItem[]>([])
const getDeliveryList = async (params: DeliveryListSearch = {}) => {
  params.isVoid = 0
  const res = await getDeliveryAllList(params)
  deliveryList.value = res.data.list
}
// 获取详情
const getDetail = () => {
  getInvoiceDetail({ invoiceId: props.checkData.invoiceId! }).then((res) => {
    form.value = res.data
    attachFiles.value = form.value.fileList ? [...form.value.fileList] : []
    if (form.value.customerId) {
      formEvent('customerID')
    }
  })
}
// 表格事件
const tableBtn = (type: string, row?: InvoiceResItemDetailList, rowIndex?: number) => {
  switch (type) {
    case 'addRow':
      form.value.detailList.push({ ...tableRow.value })
      break
    case 'delRow':
      form.value.detailList.splice(rowIndex!, 1)
      break
    case 'changeRelated':
      {
        const deliveryItem = deliveryList.value.find(
          (item) => item.deliveryOrderId === row?.deliveryOrderId
        )
        row!.deliveryDate = deliveryItem?.createdDt || ''
        row!.productName =
          deliveryItem?.detailList?.map((item) => item.materialName).join(',') || ''
        row!.amt = sumBy(deliveryItem?.detailList, (item) => item.amt) || 0
      }
      break
    default:
      break
  }
}
// 表单事件
const formEvent = (type: string) => {
  switch (type) {
    case 'customerID': {
      const customerItem = customerList.value.find(
        (item) => item.customerId === form.value.customerId
      )
      getDeliveryList({ customerName: customerItem?.customerName })
      break
    }

    default:
      break
  }
}
// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate(async (errors) => {
        if (!errors) {
          form.value.invoiceType = 1
          const delFile = differenceBy(form.value.fileList, attachFiles.value)
          const delFileIds = delFile.map((item) => item.fileId)
          form.value.fileList = attachFiles.value
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.invoiceId = undefined
          }
          if (!isEmpty(delFileIds)) {
            await batchDelUploadFile({ fileIdList: delFileIds })
          }
          form.value.invoiceDate = dayjs().format('YYYY-MM-DD')
          const tempDetail = form.value.detailList.map((item) => {
            return {
              relatedOrderId: item.deliveryOrderId,
              relatedOrderCode: item.deliveryOrderCode,
              amt: item.amt
            }
          })
          editInvoice(deleteNullObject({ ...form.value, detailList: tempDetail })).then(() => {
            Message.success((attrs.title as string).includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    case 'open':
      getCustomerList()
      if (attrs.title === '修改') {
        getDetail()
      }
      menuParam.switchEditStatus(true)
      break
    case 'cancel':
      formRef.value.resetFields()
      emit('update:visible', false)
      menuParam.switchEditStatus(false)
      break
    default:
      break
  }
}
</script>
<style scoped></style>
